<template>
	<view class="chat">
		<scroll-view :style="{ height: `${windowHeight}rpx` }" id="scrollview" scroll-y="true" :scroll-top="scrollTop" :scroll-with-animation="true" class="scroll-view">
			<!-- 聊天主体 -->
			<view id="msglistview" class="chat-body">
				<!-- 聊天记录 -->
				<view v-for="(item, index) in msgList" :key="index">
					<!-- 自己发的消息 -->
					<view class="item self" v-if="item.userContent != ''">
						<!-- 文字内容 -->
						<view class="content right">{{ item.userContent }}</view>
						<!-- 头像 -->
						<view class="avatar"></image></view>
					</view>
					<!-- 机器人发的消息 -->
					<view class="item Ai" v-if="item.botContent != ''">
						<!-- 头像 -->
						<view class="avatar"></image></view>
						<!-- 文字内容 -->
						<view class="content left">{{ item.botContent }}</view>
					</view>
				</view>
			</view>
		</scroll-view>
		<!-- 底部消息发送栏 -->
		<!-- 用来占位，防止聊天消息被发送框遮挡 -->
		<view class="chat-bottom">
			<view class="send-msg">
				<view class="uni-textarea"><textarea v-model="chatMsg" maxlength="300" :show-confirm-bar="false" auto-height></textarea></view>
				<button @click="handleSend" class="send-btn">发送</button>
			</view>
		</view>
	</view>
</template>
<script>
export default {
	data() {
		return {
			//滚动距离
			scrollTop: 0,
			userId: '',
			//发送的消息
			chatMsg: '',
			acceptId: 0,
			myAvatar: '',
			hisAvatar: '',
			
			userName: '',
			webSocket: null,
			msg: '',
			content: '',
			from:'',
			toName:'',
			msgList: [
				{
					botContent: 'hello，请问我有什么可以帮助你的吗？',
					recordId: 0,
					titleId: 0,
					userContent: '',
					userId: 0
				}
			]
		};
	},
	computed: {
		windowHeight() {
			return this.rpxTopx(uni.getSystemInfoSync().windowHeight);
		}
	},
	onLoad(options) {
		let that = this;
		this.timer = null;
		that.acceptId = options.id;
		that.hisAvatar = options.hisAvatar;
		that.toName = options.to_name;
		console.log(that.acceptId)
		that.connect();
		uni.getStorage({
			key: 'photo',
			data: that.myAvatar
		});
		// this.startPolling();
	},
	onUnload() {
		clearInterval(this.timer);
		this.webSocket.close();
		this.timer = null;
	},
	methods: {
		send() {
			let that = this;
			this.userName = uni.getStorageSync('name');
			console.log(this.userName);
			console.log(this.content)
			// 创建连接
			let from = uni.getStorageSync('userId');
			that.from = from;
			let sendData = {
				from: from, // 必须包含属性from
				from_name: this.userName, // 必须包含属性from_name
				content: that.content, // 必须包含属性content
				to: that.acceptId, // 必须包含属性to
				to_name: that.toName, // 必须包含属性to_name
				sendToAll: false // 必须包含属性sendToAll
			};
			that.webSocket.send({
				data: JSON.stringify(sendData)
			});
		},
		connect(){
			this.userName = uni.getStorageSync('userName');
			console.log(this.userName);
			// 创建连接
			let to = uni.getStorageSync('to');
			let from = uni.getStorageSync('userId');
			let to_name = uni.getStorageSync('to_name');
			let that = this;
			let ws = uni.connectSocket({
				url: 'ws://10.66.128.40:8081/huajia-backend/websocket/' + from,
				success() {
					console.log('WebSocket连接成功');
				},
				fail() {
					console.log('WebSocket连接失败');
				}
			});
			this.webSocket = ws;
			// 监听连接事件
			ws.onOpen(() => {
				console.log('WebSocket已连接');
			
				// 在连接成功后发送数据
				// const sendData = {
				// 	from: from, // 必须包含属性from
				// 	from_name: this.userName, // 必须包含属性from
				// 	content: this.content, // 必须包含属性content
				// 	to: to, // 必须包含属性to
				// 	to_name: to_name, // 必须包含属性to
				// 	sendToAll: false // 必须包含属性sendToAll
				// 	// 其他数据...
				// };
				// ws.send({
				// 	data: JSON.stringify(sendData)
				// });
			});
			
			// 监听服务器推送消息事件
			ws.onMessage(data => {
				console.log('收到消息', JSON.parse(data.data).userContent);
				let obj = {
					botContent: JSON.parse(data.data).userContent,
					recordId: 0,
					titleId: 0,
					userContent: '',
					userId: 0
				};
				that.msgList.push(obj);
				this.msg = 'data';
			});
			
			// 监听错误事件
			ws.onError(error => {
				console.log('WebSocket错误', error);
			});
			
			// 监听关闭事件
			ws.onClose(() => {
				console.log('WebSocket已关闭');
			});
			
			// 发送消息
			ws.send({
				data: 'Hello WebSocket',
				success() {
					console.log('消息发送成功');
				}
			});
		},
		// px转换成rpx
		rpxTopx(px) {
			let deviceWidth = wx.getSystemInfoSync().windowWidth;
			let rpx = (750 / deviceWidth) * Number(px);
			return Math.floor(rpx);
		},
		// 发送消息
		handleSend() {
			let that = this;
			//如果消息不为空
			if (this.chatMsg != '' || !/^\s+$/.test(this.chatMsg)) {
				let obj = {
					botContent: '',
					recordId: 0,
					titleId: 0,
					userContent: this.chatMsg,
					userId: 0
				};
				this.msgList.push(obj);
				this.content = obj;
				that.send()
				this.chatMsg = '';
			} else {
				this.$modal.showToast('不能发送空白消息');
			}
		}
	}
};
</script>
<style lang="scss" scoped>
$chatContentbgc: #c2dcff;
$sendBtnbgc: #4f7df5;

view,
button,
text,
input,
textarea {
	margin: 0;
	padding: 0;
	box-sizing: border-box;
}

/* 聊天消息 */
.chat {
	.scroll-view {
		::-webkit-scrollbar {
			display: none;
			width: 0 !important;
			height: 0 !important;
			-webkit-appearance: none;
			background: transparent;
			color: transparent;
		}

		// background-color: orange;
		background-color: #f6f6f6;

		.chat-body {
			display: flex;
			flex-direction: column;
			padding-top: 23rpx;
			// background-color:skyblue;

			.self {
				justify-content: flex-end;
			}
			.item {
				display: flex;
				padding: 23rpx 30rpx;
				// background-color: greenyellow;

				.right {
					background-color: $chatContentbgc;
				}
				.left {
					background-color: #ffffff;
				}
				// 聊天消息的三角形
				.right::after {
					position: absolute;
					display: inline-block;
					content: '';
					width: 0;
					height: 0;
					left: 100%;
					top: 10px;
					border: 12rpx solid transparent;
					border-left: 12rpx solid $chatContentbgc;
				}

				.left::after {
					position: absolute;
					display: inline-block;
					content: '';
					width: 0;
					height: 0;
					top: 10px;
					right: 100%;
					border: 12rpx solid transparent;
					border-right: 12rpx solid #ffffff;
				}

				.content {
					position: relative;
					max-width: 486rpx;
					border-radius: 8rpx;
					word-wrap: break-word;
					padding: 24rpx 24rpx;
					margin: 0 24rpx;
					border-radius: 5px;
					font-size: 32rpx;
					font-family: PingFang SC;
					font-weight: 500;
					color: #333333;
					line-height: 42rpx;
				}

				.avatar {
					display: flex;
					justify-content: center;
					width: 78rpx;
					height: 78rpx;
					background: $sendBtnbgc;
					border-radius: 8rpx;
					overflow: hidden;
					image {
						align-self: center;
					}
				}
			}
		}
	}

	/* 底部聊天发送栏 */
	.chat-bottom {
		width: 100%;
		height: 177rpx;
		background: #f4f5f7;

		.send-msg {
			display: flex;
			align-items: flex-end;
			padding: 16rpx 30rpx;
			width: 100%;
			min-height: 177rpx;
			position: fixed;
			bottom: 0;
			background: #ededed;
		}

		.uni-textarea {
			padding-bottom: 70rpx;

			textarea {
				width: 537rpx;
				min-height: 75rpx;
				max-height: 500rpx;
				background: #ffffff;
				border-radius: 8rpx;
				font-size: 32rpx;
				font-family: PingFang SC;
				color: #333333;
				line-height: 43rpx;
				padding: 5rpx 8rpx;
			}
		}

		.send-btn {
			display: flex;
			align-items: center;
			justify-content: center;
			margin-bottom: 70rpx;
			margin-left: 25rpx;
			width: 128rpx;
			height: 75rpx;
			background: $sendBtnbgc;
			border-radius: 8rpx;
			font-size: 28rpx;
			font-family: PingFang SC;
			font-weight: 500;
			color: #ffffff;
			line-height: 28rpx;
		}
	}
}
</style>
